/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * MainFrame.java
 *
 * Created on 22-mar-2011, 9:06:43
 */

package com.infinityk.tangentgenerator;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DropMode;

/**
 *
 * @author Asier
 */
public class MainFrame extends javax.swing.JFrame {

    /** Creates new form MainFrame */
    public MainFrame() {
        initComponents();
        inputText.setDragEnabled(true);
        inputText.setDropMode(DropMode.INSERT);
        inputText.setTransferHandler( new FileDropTransferHandler(this) );
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        inputText = new javax.swing.JTextField();
        inputButton = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        outputText = new javax.swing.JTextField();
        outputButton = new javax.swing.JButton();
        okButton = new javax.swing.JButton();
        statusText = new javax.swing.JTextField();
        bigEndianMetadaCheck = new javax.swing.JCheckBox();
        bigEndianDataCheck = new javax.swing.JCheckBox();
        saveTangentsCheck = new javax.swing.JCheckBox();
        saveNormalsCheck = new javax.swing.JCheckBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("InfinityK - tangent generator");

        jLabel1.setText("Input:");

        inputButton.setText("Select");
        inputButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                inputButtonActionPerformed(evt);
            }
        });

        jLabel2.setText("Output:");

        outputButton.setText("Select");
        outputButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                outputButtonActionPerformed(evt);
            }
        });

        okButton.setText("OK");
        okButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                okButtonActionPerformed(evt);
            }
        });

        statusText.setEditable(false);
        statusText.setText("Ready");

        bigEndianMetadaCheck.setText("BigEndian metadata");

        bigEndianDataCheck.setText("BigEndian data");

        saveTangentsCheck.setText("Save tangents");

        saveNormalsCheck.setSelected(true);
        saveNormalsCheck.setText("Save normals");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(inputText, javax.swing.GroupLayout.DEFAULT_SIZE, 237, Short.MAX_VALUE)
                            .addComponent(outputText, javax.swing.GroupLayout.DEFAULT_SIZE, 237, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(inputButton)
                            .addComponent(outputButton)))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(okButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(statusText, javax.swing.GroupLayout.DEFAULT_SIZE, 293, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(bigEndianDataCheck)
                            .addComponent(bigEndianMetadaCheck))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 132, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(saveNormalsCheck)
                            .addComponent(saveTangentsCheck))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(inputText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(inputButton)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(outputText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(outputButton))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(bigEndianMetadaCheck)
                    .addComponent(saveNormalsCheck))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(bigEndianDataCheck)
                    .addComponent(saveTangentsCheck))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(okButton)
                    .addComponent(statusText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void inputButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_inputButtonActionPerformed
        String path = FileUtils.selectFile(this, "Open", FileUtils.objFilter, null);
        if (path != null){
            inputText.setText(path);
            calculateOutputPath(path);
        }
    }//GEN-LAST:event_inputButtonActionPerformed

    private void outputButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_outputButtonActionPerformed
        String path = FileUtils.selectNonExistingFile(this, ".msh");
        if(path != null){
            outputText.setText(path);
        }
    }//GEN-LAST:event_outputButtonActionPerformed

    private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed
        FileOutputStream fos = null;
        try {
            statusText.setText("Reading model");
            String content = new String(FileUtils.getBytesFromFile(new File(inputText.getText())));

            statusText.setText("Parsing");
            Mesh mesh = new Mesh();
            mesh.parse(content);

            boolean bigEndianMetada = bigEndianMetadaCheck.isSelected();
            boolean bigEndianData = bigEndianDataCheck.isSelected();
            boolean saveNormals = saveNormalsCheck.isSelected();
            boolean saveTangents = saveTangentsCheck.isSelected();

            if(saveTangents){
                statusText.setText("Generating tangents");
                mesh.generateTangents();
            }

            statusText.setText("Writing");
            File f = new File(outputText.getText());
            fos = new FileOutputStream(f, false);
            fos.write( mesh.serialize(bigEndianMetada,bigEndianData,saveNormals,saveTangents));
           
            fos.flush();
            
            statusText.setText("Ready");
        } catch (Exception ex) {
            statusText.setText("Error: " + ex.toString());
            Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
        }finally{

            if (fos != null) { try{ fos.close(); } catch(Exception e){} }
            
        }

    }//GEN-LAST:event_okButtonActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JCheckBox bigEndianDataCheck;
    private javax.swing.JCheckBox bigEndianMetadaCheck;
    private javax.swing.JButton inputButton;
    private javax.swing.JTextField inputText;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JButton okButton;
    private javax.swing.JButton outputButton;
    private javax.swing.JTextField outputText;
    private javax.swing.JCheckBox saveNormalsCheck;
    private javax.swing.JCheckBox saveTangentsCheck;
    private javax.swing.JTextField statusText;
    // End of variables declaration//GEN-END:variables

    public void calculateOutputPath(String path) {
        if (path == null) {return;}
        String outputPath = path;
        int lastPoint = path.lastIndexOf('.');
        if (lastPoint != -1){
            outputPath = path.substring(0, lastPoint) + ".msh";
        }else{
            outputPath +=  ".msh";
        }
        outputText.setText(outputPath);
    }

}
